package com.example.geek.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.example.geek.R;
import com.example.geek.activity.HomeActivity;
import com.example.geek.activity.LoginActivity;
import com.example.geek.adapter.HomeAdapter;
import com.example.geek.entity.PostCategoryResponse;
import com.example.geek.entity.CategoryEntity;
import com.flyco.tablayout.SlidingTabLayout;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HomeFragment extends Fragment {
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private String[] mTitles;
    private ViewPager viewPager;
    private SlidingTabLayout slidingTabLayout;

    public HomeFragment() {
    }

    public static HomeFragment newInstance() {
        HomeFragment fragment = new HomeFragment();
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_home, container, false);
        viewPager = v.findViewById(R.id.fixedViewPager);
        slidingTabLayout = v.findViewById(R.id.slidingTabLayout);
        return v;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getPostCategoryList();
    }

    private void getPostCategoryList() {
        SharedPreferences sp = getActivity().getSharedPreferences("sp_ttit", Context.MODE_PRIVATE);
        String token = sp.getString("token", "");
        if (!token.isEmpty()) {
            HashMap<String, Object> params = new HashMap<>();
            params.put("token", token);
            OkHttpClient client = new OkHttpClient.Builder()
                    .build();
            String requestUrl = "http://47.112.180.188:8080/renren-fast/app/videocategory/list";
            String url = getAppendUrl(requestUrl, params);
            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("token", token)
                    .get()
                    .build();
            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("onFailure", e.getMessage());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final String result = response.body().string();
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        String code = jsonObject.getString("code");
                        if (code.equals("401")) {
                            Intent in = new Intent(getContext(), LoginActivity.class);
                            startActivity(in);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            PostCategoryResponse postCategoryResponse = new Gson().fromJson(result, PostCategoryResponse.class);
                            if (postCategoryResponse != null && postCategoryResponse.getCode() == 0) {
                                List<CategoryEntity> list = postCategoryResponse.getPage().getList();
                                if (list != null && list.size() > 0) {
                                    mTitles = new String[list.size()];
                                    for (int i = 0; i <list.size() ; i++) {
                                        mTitles[i] = list.get(i).getCategoryName();
                                        mFragments.add(PostFragment.newInstance(list.get(i).getCategoryId()));
                                    }
                                    viewPager.setOffscreenPageLimit(mFragments.size());
                                    viewPager.setAdapter(new HomeAdapter(getFragmentManager(), mTitles, mFragments));
                                    viewPager.setCurrentItem(1);
                                    slidingTabLayout.setViewPager(viewPager);
                                }
                            }
                        }
                    });
                }
            });
        } else {
            Intent intent = new Intent(getContext(), HomeActivity.class);
            startActivity(intent);
        }
    }

    private String getAppendUrl(String url, Map<String, Object> map) {
        if (map != null && !map.isEmpty()) {
            StringBuffer buffer = new StringBuffer();
            Iterator<Entry<String, Object>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, Object> entry = iterator.next();
                if (buffer.toString().isEmpty()) {
                    buffer.append("?");
                } else {
                    buffer.append("&");
                }
                buffer.append(entry.getKey()).append("=").append(entry.getValue());
            }
            url += buffer.toString();
        }
        return url;
    }
}
